package cn.donting.file;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class FileTaskManger {
    //30 分钟
    private int removeTime=30*60*1000;

    private HashMap<String, FileTask> taskHashMap = new HashMap<>();

    public synchronized void push(FileTask fileTask) {
        taskHashMap.put(fileTask.getTaskId(), fileTask);
        check();
    }

    public synchronized FileTask getFileTask(String taskId) {
        FileTask fileTask = taskHashMap.get(taskId);
        check();
        return fileTask;
    }

    public synchronized FileTask remove(String taskId) {
        FileTask remove = taskHashMap.remove(taskId);
        check();
        return remove;
    }

    private synchronized void check() {
        Set<Map.Entry<String, FileTask>> entries = taskHashMap.entrySet();
        ArrayList<String> removeTaskId=new ArrayList<>();
        for (Map.Entry<String, FileTask> entry : entries) {
            FileTask fileTask = entry.getValue();
            if (fileTask.getEndTime() != 0) {
                long subTime = System.currentTimeMillis() - fileTask.getEndTime();
                if(subTime>removeTime){
                    removeTaskId.add(fileTask.taskId);
                }
            }
        }
        for (String taskId : removeTaskId) {
            taskHashMap.remove(taskId);
        }
    }
}
